package com.gateway.fliter;


import com.gateway.utils.AesUtils;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.io.InputStream;

@Component
public class SignReponseDataFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "post";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //获取到微服务接口返回的数据，进行加密

        //1.获取流
        InputStream inputStream = RequestContext.getCurrentContext().getResponseDataStream();
//        String body = IOUtils.toString(inputStream);

        try {
            byte[] bytes = StreamUtils.copyToByteArray(inputStream);
            String body = new String(bytes,"UTF8");

            System.out.println("接口返回的参数：" + body);

            //加密处理
            String key = AesUtils.getRandomStringKey();
            String iv = AesUtils.getRandomStringIv();
            String signBody = AesUtils.encrypt(body,key,iv);

            System.out.println("接口加密处理返回的参数：" + signBody);


            RequestContext.getCurrentContext().setResponseBody(signBody);


        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }


        return null;
    }
}
